<!-- JavaScript neccessary for the tree -->
$(function () {
    $.ajaxSetup({cache:false});//这个是为了树的准确性做的一个缓存区清理的工作  
	// Settings up the tree - using $(selector).jstree(options);
	// All those configuration options are documented in the _docs folder
	$("#jsTree")
		.jstree({ 
			// the list of plugins to include
			"plugins" : [ "themes", "json_data", "ui", "crrm", "cookies", "dnd", "search", "types", "hotkeys", "contextmenu" ],
			// Plugin configuration

			// I usually configure the plugin that handles the data first - in this case JSON as it is most common
			"json_data" : { 
				// I chose an ajax enabled tree - again - as this is most common, and maybe a bit more complex
				// All the options are the same as jQuery's except for `data` which CAN (not should) be a function
				"ajax" : {
					// the URL to fetch the data
					"url" : "/tree.jspx",
					// this function is executed in the instance's scope (this refers to the tree instance)
					// the parameter is the node being loaded (may be -1, 0, or undefined when loading the root nodes)
					"data" : function (n) { 
						// the result is fed to the AJAX request `data` option
						return { 
							"action" : "get_children", 
							"id" : n.attr ? n.attr("id") : "", 
							"temp" : new Date().getTime()
						}; 
					},
					"success" : function (r) {
						if ((typeof r.error) != 'undefined') {
							alert(r.error);
						}
					}
				}
			},
			// Configuring the search plugin
			"search" : {
				// As this has been a common question - async search
				// Same as above - the `ajax` config option is actually jQuery's object (only `data` can be a function)
				"ajax" : {
					"url" : "/tree.jspx",
					// You get the search string as a parameter
					"data" : function (str) {
						return { 
							"action" : "search", 
							"search_str" : str 
						}; 
					}
				}
			},
			// Using types - most of the time this is an overkill
			// Still meny people use them - here is how
			"types" : {
				// I set both options to -2, as I do not need depth and children count checking
				// Those two checks may slow jstree a lot, so use only when needed
				"max_depth" : -2,
				"max_children" : -2,
				// I want only `drive` nodes to be root nodes 
				// This will prevent moving or creating any other type as a root node
				"valid_children" : [ "drive", "folder" ],
				"types" : {
					// The default type
					"default" : {
						// I want this type to have no children (so only leaf nodes)
						// In my case - those are files
						"valid_children" : "none",
						// If we specify an icon for the default type it WILL OVERRIDE the theme icons
						"icon" : {
							"image" : "../js/jstree/file.png"
						}
					},
					// The `folder` type
					"folder" : {
						// can have files and other folders inside of it, but NOT `drive` nodes
						"valid_children" : [ "default", "folder" ],
						"icon" : {
							"image" : "../js/jstree/folder.png"
						}
					},
					// The `drive` nodes 
					"drive" : {
						// can have files and folders inside, but NOT other `drive` nodes
						"valid_children" : [ "default", "folder" ],
						"icon" : {
							"image" : "../js/jstree/root.png"
						},
						// those options prevent the functions with the same name to be used on the `drive` type nodes
						// internally the `before` event is used
						"start_drag" : false,
						"move_node" : false,
						"delete_node" : false,
						"remove" : false
					}
				}
			},
			// For UI & core - the nodes to initially select and open will be overwritten by the cookie plugin

			// the UI plugin - it handles selecting/deselecting/hovering nodes
			"ui" : {
				"select_limit" : 1,
				// this makes the node with ID node_4 selected onload
				// Example: "initially_select" : [ "node_4" ]
				"initially_select" : [  ]
			},
			"contextmenu" : {     
				"items" : {
					"create" : null ,
					"rename" : null ,
					"remove" : null ,
					"ccp" : null,
					"myCreateCatalog" : {
						"separator_before"	: false,
						"separator_after"	: false,
						"label"				: "新建分类",
						"action"			: function (obj) { this.create(obj, "last", { "attr" : { "rel" : "folder" } }); }
					},
					"myCreateTestCase" : {
						"separator_before"	: false,
						"separator_after"	: true,
						"label"				: "新建用例",
						"action"			: function (obj) { this.create(obj); }
					},
					"myRename" : {
						"separator_before"	: false,
						"separator_after"	: false,
						"label"				: "修改",
						"action"			: function (obj) { this.rename(obj); }
					},
					"myRemove" : {
						"separator_before"	: false,
						"icon"				: false,
						"separator_after"	: false,
						"label"				: "删除",
						"action"			: function (obj) { if(this.is_selected(obj)) { this.remove(); } else { this.remove(obj); } }
					},
					"myCut" : {
						"separator_before"	: true,
						"icon"				: false,
						"separator_after"	: false,
						"label"				: "剪切",
						"action"			: function (obj) { this.cut(obj); }
					},
					"myCopy" : {
						"separator_before"	: false,
						"icon"				: false,
						"separator_after"	: false,
						"label"				: "复制",
						"action"			: function (obj) { this.copy(obj); }
					},
					"myPaste" : {
						"separator_before"	: false,
						"icon"				: false,
						"separator_after"	: false,
						"label"				: "粘贴",
						"action"			: function (obj) { this.paste(obj); }
					}
				}     
			},
			// the core plugin - not many options here
			"core" : { 
				// just open those two nodes up
				// as this is an AJAX enabled tree, both will be downloaded from the server
				// Example: "initially_open" : [ "node_2" , "node_3" ]
				"initially_open" : [  ] 
			}
		})
		.bind("create.jstree", function (e, data) {
			$.post(
				"/tree.jspx", 
				{ 
					"action" : "create_node", 
					"rel" : data.rslt.obj.attr("rel"),
					"pid" : data.rslt.parent.attr("id"), 
					"newText" : data.rslt.name,
					"position" : data.rslt.position
				}, 
				function (r) {
					if(r.status) {
						$(data.rslt.obj).attr("id", r.id);
					}
					else {
						$.jstree.rollback(data.rlbk);
						alert(r.error);
					}
				}
			);
		})
		.bind("remove.jstree", function (e, data) {
			data.rslt.obj.each(function () {
				$.ajax({
					async : false,
					type: 'POST',
					url: "/tree.jspx",
					data : { 
						"action" : "remove_node", 
						"rel" : this.rel,
						"id" : this.id
					}, 
					success : function (r) {
						if(!r.status) {
							data.inst.refresh();
							alert(r.error);
						}
					}
				});
			});
		})
		.bind("rename.jstree", function (e, data) {
			$.post(
				"/tree.jspx", 
				{ 
					"action" : "rename_node", 
					"rel" : data.rslt.obj.attr("rel"),
					"id" : data.rslt.obj.attr("id"),
					"newText" : data.rslt.new_name
				}, 
				function (r) {
					if(!r.status) {
						$.jstree.rollback(data.rlbk);
						alert(r.error);
					}
				}
			);
		})
		.bind("move_node.jstree", function (e, data) {
			data.rslt.o.each(function (i) {
				pNodeID=data.rslt.np.attr("id");
				if (pNodeID=="jsTree") {
					pNodeID="";
				}

				$.ajax({
					async : false,
					type: 'POST',
					url: "/tree.jspx",
					data : { 
						"action" : "move_node", 
						"pid" : pNodeID, 
						"id" : $(this).attr("id"),
						"rel" : this.rel,
						"position" : data.rslt.cp + i,
						"title" : data.rslt.name,
						"copy" : data.rslt.cy ? 1 : 0
					},
					success : function (r) {
						if(!r.status) {
							$.jstree.rollback(data.rlbk);
							alert(r.error);
						}
						else {
							$(data.rslt.oc).attr("id", r.id);
							if(data.rslt.cy && $(data.rslt.oc).children("UL").length) {
								data.inst.refresh(data.inst._get_parent(data.rslt.oc));
							}
						}
						$("#analyze").click();
					}
				});
			});
		})
		.bind("select_node.jstree", function (e, data) {
			var uriStr;
			if (data.rslt.obj.attr("rel")=="folder") {
				uriStr="/testCaseMgt/catalog.jspx?action=query&id=" + data.rslt.obj.attr("id");				
			} else {
				uriStr="/testCaseMgt/testCase.jspx?action=query&id=" + data.rslt.obj.attr("id");
			}
			window.parent.frames["mainFrame"].location.href = uriStr;
		});
});

$(function () { 
	$("#mmenu input").click(function () {
		switch(this.id) {
			case "add_default":
			case "add_folder":
				$("#jsTree").jstree("create", null, "last", { "attr" : { "rel" : this.id.toString().replace("add_", "") } });
				break;
			case "search":
				$("#jsTree").jstree("search", document.getElementById("text").value);
				break;
			case "text": break;
			default:
				$("#jsTree").jstree(this.id);
				break;
		}
	});
});

// 创建树节点，pid:带#号的父分类ID，例如："#2c972a33382c3c0701382d0ec2d500a4" 或 "-1"(添加到根), id:分类ID, rel:显示的图标folder为文件夹file为文件, text:显示的内容
function createTreeNode(pid, id, rel, text) {
	// 判断是否向从未显示过的节点下添加子节点
	if (!($.jstree._reference($("#jsTree"))._get_node(pid))) {
		return;
	}

	var nodes = $.jstree._reference($("#jsTree"))._get_children("#"+pid);
	if (nodes.length==0) {
		$("#jsTree").jstree("open_node", pid, false, true);
	}

	if (rel=="folder") {
		js = {"attr":{"id":id,"rel":"folder"},"data":text,"state":""};
	} else if (rel=="file") {
		js = {"attr":{"id":id,"rel":"default"},"data":text,"state":""};
	}
	$("#jsTree").jstree("create_node", pid, "first", js, false, false, true);
}

// 删除树节点
function deleteTreeNode(id) {
	$("#jsTree").jstree("delete_node", "#"+id);
}

// 更新树节点显示内容,pid:带#号的父分类ID，例如："#2c972a33382c3c0701382d0ec2d500a4" 或 "-1"(父分类为根), id:分类ID, text:显示的内容
function updateTreeNode(pid, id, text) {
	$("#jsTree").jstree("rename_node", "#"+id, text);

	var pNode=$.jstree._reference($("#jsTree"))._get_parent("#"+id);
	if (pNode==-1) {
		pNodeID=-1;
	} else {
		pNodeID=pNode.attr("id");
	}
	if (("#"+pNodeID)!=pid) {
		// 判断是否向从未显示过的节点下移动子节点
		if (!($.jstree._reference($("#jsTree"))._get_node(pid))) {
			$("#jsTree").jstree("delete_node", "#"+id);
			return;
		}

		$("#jsTree").jstree("move_node", "#"+id, pid);
	}
}
